package grow

import (
	"server/game/cache"
	"server/game/itypes"
	"server/game/model"
	"server/share"
	"server/share/config"
	"server/social"
	"server/social/graph"

	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/errors"
)

func init() {
	Register(&help{})
}

const graphHelpHeroes = "HelpHeroes"

type help struct {
}

func (this *help) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*help, *context.Context) interface{})
	return f(this, handle)
}

/**
 * @name setHelp
 * @param string unitID  助战单位ID
 * @param int siteID 助战单位位置
 * 设置玩家助战单位
 */
func (this *help) SetHelp(c *context.Context) any {
	unitID := c.GetString("unitID")
	siteID := int8(c.GetInt32("siteID"))
	if siteID < 1 || siteID > 3 {
		return errors.ErrArgEmpty
	}
	//if unitID == "" {
	//	return errors.ErrArgEmpty
	//}
	items := cache.GetItems(c.Player.Updater)

	roleDoc := cache.GetRole(c.Player.Updater)
	role := roleDoc.All()
	helpsData := role.GetHelp()

	helpUnit := model.RoleHelp{}
	if unitID != "" {
		data := items.Get(unitID)
		if data == nil {
			return errors.ErrDataNotExists
		}
		for _, d := range helpsData {
			if d.OID == unitID {
				return c.Errorf(0, "已经存在")
			}
		}
		helpUnit.OID = data.OID
		helpUnit.IID = data.IID
		helpUnit.Lv = data.Attach.GetInt32(model.AttachUnitLv)
		helpUnit.SLv = data.Attach.GetInt32(model.AttachUnitSlv)
	}

	helpsData[siteID] = helpUnit
	roleDoc.Set("HelpUnit", helpsData)
	//同步到好友列表
	//var helpsList []string
	//for _, v := range helpsData {
	//	helpsList = append(helpsList, fmt.Sprintf("%d|%d|%d", v.IID, v.Lv, v.SLv))
	//}

	//_ = social.Graph.Modify(c.Uid(), func(player *graph.Player) error {
	//	player.Set(graphHelpHeroes, strings.Join(helpsList, ";"))
	//	return nil
	//})

	return true
}

/**
 * @name helpList
 * @param string key 额外字段,多个以","分割
 * 助战列表
 */

type HelpListReply struct {
	share.Player `bson:"inline"`
	HelpUnit     model.RoleHelpMgr `json:"helpUnit" bson:"helpUnit"` //助阵列表
	//Info     map[string]any
}

const HelpListMaxSearchNum = 30

func (this *help) HelpList(c *context.Context) any {

	var ids []string
	var i int32
	social.Graph.Range(c.Uid(), graph.RelationFriend, func(g graph.Getter) bool {
		ids = append(ids, g.Fid())
		i++
		if i > HelpListMaxSearchNum {
			return false
		}
		//p := g.Player()
		//ids = append(ids,p.)
		//
		//s := p.GetString(graphHelpHeroes)
		//if s == "" {
		//	return true
		//}
		//k := g.Fid()
		//ids = append(ids, k)
		//v := &HelpListReply{Info: map[string]any{}}
		//v.Info[define.FriendInfoHelps] = s
		//rows[k] = v
		return true
	})
	var reply []*HelpListReply
	var rows []*HelpListReply
	if len(ids) == 0 {
		return rows
	}

	tx := db.Model(&model.Role{})
	sp := share.Player{}
	fields := sp.GetDBFields()
	fields = append(fields, "helpUnit")
	tx = tx.Select(fields...)
	tx = tx.Where(ids)
	if tx = tx.Find(&rows); tx.Error != nil {
		return tx.Error
	}

	//ps, err := cache.GetPlayers(ids)
	//if err != nil {
	//	return err
	//}

	for _, p := range rows {
		if len(p.HelpUnit) > 0 {
			reply = append(reply, p)
		}
	}

	return reply
}

/**
 * @name usehelp
 * @param string uid 角色唯一ID
 * 使用助战
 */

func (this *help) Usehelp(c *context.Context) any {
	uid := c.GetString("uid")
	dailyDoc := itypes.Daily.Handle(c.Player.Updater)
	dailyData := dailyDoc.All()
	var data []string
	for _, v := range dailyData.UseHelp {
		if v == uid {
			return c.Errorf(0, "单位已经被使用过了")
		}
		data = append(data, v)
	}
	base := config.Data.Base["assistCount"]
	if len(data) >= int(base.Val) {
		return c.Errorf(0, "今日助战已达最大次数")
	}
	data = append(data, uid)
	dailyDoc.Set("UseHelp", data)
	c.Player.Emit(config.Data.Events.FriendHelpTimes, 1)
	return nil
}
